//
//  Status.swift
//  WeiBo
//
//  Created by 江潘 on 15/6/30.
//  Copyright © 2015年 江潘. All rights reserved.
//

import UIKit
import SDWebImage

private  let urlString = "2/statuses/home_timeline.json"

class Status: NSObject {
    
    var created_at:String?
    var id:Int = 0
    var text:String?
    var source:String?
    var pic_urls:[[String:String]]?
    var imgURLS:[NSURL]?
    var user:UserStatus?
    
    static let properties = ["created_at","id","text","source","pic_urls","user"]
    
    init(Dict:[String:AnyObject]){
    
        super.init()
        
        for key in Status.properties{
            
            if Dict[key] != nil && key != "user"{
                
               setValue(Dict[key], forKey: key)
            } else if key == "user" && Dict[key] != nil{
               user = UserStatus(Dict: Dict["user"] as! [String:AnyObject])
            }
        }
    }
    
    override var description:String {
    
        let dict = dictionaryWithValuesForKeys(Status.properties)
        
        return  "\(dict)\n"
    }
    
    class func loadStatus(finished:(result:[Status]?,error:NSError?)->()){
        
        let params = ["access_token":sharedAccount!.access_token]
        
        NetworkTools.sharedNewworkTools().GET(urlString, parameters: params, success: { (_, JSON) -> Void in
            
            if let InfoData = JSON["statuses"] as? [[String:AnyObject]]{
            
             let StatusList = Status.convertStatusList(InfoData)
            
             cacheWebImg(StatusList!, fininshed:finished)
                
              return
            }
            // 返回解析后的空数据
              finished(result: nil, error: nil)
            
            }) { (_, error) -> Void in
                
                finished(result: nil,error: error)
        }
    }
    
    private class func cacheWebImg(list:[Status],fininshed:(result:[Status]?,error:NSError?)->()){
        
        var arrayM_URLS = [NSURL]()
        
        // 创建组队列
        let group = dispatch_group_create()
        
        for status:Status in list{
    
            if status.pic_urls != nil {
                
                for urls in status.pic_urls! {
                
                    arrayM_URLS.append(NSURL(string: urls["thumbnail_pic"]!)!)
                    
                    status.imgURLS = arrayM_URLS
                    
                    // 进入组队列
                    dispatch_group_enter(group)
                    
                    SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urls["thumbnail_pic"]!), options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in
                        
                    dispatch_group_leave(group)
                        // 执行完block后要离开组队列
                    })
                }
                
                arrayM_URLS.removeAll()
                
                continue
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            
            print("缓存图片完成--\(NSHomeDirectory())")
            
            fininshed(result: list, error: nil)
        })
    }
    
    private class func convertStatusList(array:[[String:AnyObject]]) ->[Status]? {
        var arrayM = [Status]()
        if array.isEmpty{
             return nil
        }
    
        for dict in array {
            arrayM.append(Status(Dict: dict))
        }
       return arrayM
    }
}
